// pages/mall/order/order.js

const app = getApp();
var spManger = require('../../data/ShopCartManager.js');
var canClick = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canClick: true,
    goodsList: null,
    totalPrice: 0,
    totalPriceOld: 0,
    RemarksValue: '',
    defaultAddress: null,
    integral: false,
    integralNum: 0,
    integralNumOld: 0,
    integralChange: false,
    shopName: '',
    couponNames: [], //优惠券名称列表
    coupins: [],
    couponIndex: 0,
    PayType: 1, //0：积分，1：微信支付
    UseIntegral: 0, // 0：不使用积分，1: 使用积分
    currentCoupon: null, //当前选择得优惠券模型
    couponAmount: 0, //当前优惠得金额
    shipAmount: 0, //当前运费
    thisShowCount: 0, //重新打开小程序后，第2次，由于app.gloab有数据，这样就会造成再结算时，会出现两次计算运费，1次是获取完地址列表后，一次是onshow（）.
    erroMsg: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let self = this;
    wx.hideShareMenu()
    this.setData({
      goodsList: JSON.parse(options.carGoodsList)
    });
    console.log(this.data.goodsList)
    this.data.goodsList.forEach((v, i) => {
      this.data.totalPrice += Number(v.SkuDetail.SallPrice) * v.SaleNum;
    });
    this.setData({
      totalPrice: this.data.totalPrice.toFixed(2),
      totalPriceOld: this.data.totalPrice.toFixed(2),
      shopName: app.globalData.userInfo.ShopName
    });
    this.getUserCoupons();
    this.GetConsigneeList();



  },
  //  获取地址信息 有默认地址显示默认地址
  GetConsigneeList: function() {
    var that = this;
    wx.showLoading({
      title: '读取地址中...',
    })
    wx.request({
      //url: app.appSetting.host + "/api/MobileMall/index?ShopID=1AD227F46DFB1666",
      url: app.appSetting.host + "/api/ConSignee/GetList?userid=" + app.globalData.userInfo.Id,
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.Code = 200 && res.data.Message == '') {
          res.data.Data.forEach((v, i) => {
            if (v.IsDefault == 1) {
              app.globalData.defaultAddress = v;
            }
          });
          that.setData({
            defaultAddress: app.globalData.defaultAddress,
            app: {
              globalData: {
                defaultAddress: app.globalData.defaultAddress
              }
            }
          });
          that.getShipAmount();
        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none'
          })
        }
      }
    })
  },

  getUserCoupons: function() {
    var that = this;
    wx.showLoading({
      title: '读取优惠券中 ',
    })
    wx.request({
      url: app.appSetting.host + "/api/Marketing/GetUserCoupon?userid=" + app.globalData.userInfo.Id,
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.Code = 200 && res.data.Message == '') {
          var tempList = []; //组成下拉列表名称
          tempList.push('请选择');
          res.data.Data.forEach((v, i) => {
            tempList.push(v.CouponName);
          })
          that.setData({
            coupons: res.data.Data,
            couponNames: tempList
          })
        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none'
          })
        }
      }
    })
  },
  bindViewEvent: function(e) {
    console.log(e);
    this.setData({
      totalPrice: (Number(this.data.totalPriceOld) + Number(this.data.shipAmount)).toFixed(2),
      couponAmount: 0,
      currentCoupon: null,
      couponIndex: 0
    })
    var couponIndex = Number(e.detail.value);
    if (couponIndex == 0)
      return;
    var coupon = this.data.coupons[couponIndex - 1];
    var _couponAmount = 0;
    //开始计算优惠金额currentCoupon
    if (coupon.CouponType == 1) {
      //满减券
      if (this.data.totalPriceOld < coupon.MinOrderAmount) {
        wx.showToast({
          title: '未达到满减金额',
          icon: 'none'
        })
        return
      } else {
        _couponAmount = coupon.DelAmount;
      }
    } else if (coupon.CouponType == 2) {
      //折扣券
      _couponAmount = (((100 - coupon.Discount) / 100) * this.data.totalPriceOld).toFixed(2);
      //测试如果是1分钱得话
      if (_couponAmount < 0.01)
        _couponAmount = 0.01;
    }
    this.setData({
      totalPrice: (Number(this.data.totalPrice) - Number(_couponAmount)).toFixed(2),
      couponAmount: _couponAmount,
      currentCoupon: coupon,
      couponIndex: couponIndex
    })
  },
  bindSelect: function(e) {
    console.log(e);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    canClick=true;
    this.setData({
      defaultAddress: app.globalData.defaultAddress,
      erroMsg: '',
      thisShowCount: this.data.thisShowCount + 1
    });
    console.log(this.data.thisShowCount);
    if (this.data.thisShowCount > 1)
      this.getShipAmount();
  },
  //获取运费
  getShipAmount: function() {
    if (app.globalData.defaultAddress == null)
      return false;
      //恢复总金额为商品金额-优惠金额，防止累加运费
    this.setData({
      totalPrice:(Number(this.data.totalPriceOld)-Number(this.data.couponAmount)).toFixed(2)
    });
    var products = [];
    this.data.goodsList.forEach((v, i) => {
      products.push({
        ProvinceCode: app.globalData.defaultAddress.ProvinceCode,
        ProductName: v.SkuDetail.ProductName,
        ProductId: v.ProductId,
        SaleNum: v.SaleNum,
        Product_SkuId: v.Product_SkuId,
        Weight: v.SkuDetail.Weight,
        ShippingTemplateId: v.SkuDetail.ShippingTemplateId
      })
    });
    var that = this;
    wx.showLoading({
      title: '计算运费中',
    })
    wx.request({
      url: app.appSetting.host + "/api/Order/CountShipAmount",
      data: {
        Spid: app.appSetting.spid,
        UserId: app.globalData.userInfo.Id,
        TotalProductAmount: that.data.totalPriceOld,
        ProvinceCode: app.globalData.defaultAddress.ProvinceCode,
        Products: products
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.Code = 200 && res.data.Message == '') {
          that.setData({
            shipAmount: res.data.Data,
            totalPrice: (Number(that.data.totalPrice) + Number(res.data.Data)).toFixed(2)
          });

        } else {
          wx.showToast({
            title: res.data.Message,
            icon: 'none'
          })
          that.setData({
            erroMsg: res.data.Message
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  goToAddress() {
    wx.navigateTo({
      url: "/pages/selectprovince/user_address_list/user_address_list?type=1",
    })
  },
  createOrder() {
    let self = this;
    if(!canClick)
      return false;
    if (canClick) {
      canClick = false;
      if (this.data.erroMsg != '') {
        wx.showToast({
          title: this.data.erroMsg,
          icon: 'none'
        })
        canClick=true;
        return
      }
      if (!app.globalData.defaultAddress) {
        wx.showToast({
          title: '请选择地址',
          icon: 'none'
        })
        canClick = true;
        return
      }
      var products = [];
      this.data.goodsList.forEach((v, i) => {
        products.push({
          ProductId: v.ProductId,
          SaleNum: v.SaleNum,
          Product_SkuId: v.Product_SkuId,
        })
      });
      var model = {};
      model.Spid = app.appSetting.spid;
      model.Said = app.appSetting.said;
      model.UserId = app.globalData.userInfo.Id;
      model.ConsigneeId = app.globalData.defaultAddress.Id;
      model.ShipAmount = this.data.shipAmount;
      model.CouponId = this.data.currentCoupon == null ? 0 : this.data.currentCoupon.CouponId;
      model.Remarks = this.data.RemarksValue;
      model.ToalAmount = this.data.totalPrice;
      model.AppType = 1;
      model.Api_CreateOrder_ProductItems = products;

      wx.showLoading({
        title: '创建订单中...',
      })
      wx.request({
        url: app.appSetting.host + "/api/Order/CreateOrder_Cart",
        data: model,
        method: 'POST',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function (res) {
          console.log(res);
          wx.hideLoading();
          if (res.data.Code = 200 && res.data.Message == '') {
            wx.requestPayment({
              'timeStamp': res.data.Data.PayParamater.TimeStamp,
              'nonceStr': res.data.Data.PayParamater.NonceStr,
              'package': res.data.Data.PayParamater.Package,
              'signType': res.data.Data.PayParamater.SignType,
              'paySign': res.data.Data.PayParamater.PaySign,
              success: function (_res) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'none',
                  success: function () {
                    wx.redirectTo({
                      url: "/pages/pay_success/pay_success?payInfo=" + JSON.stringify({
                        orderId: res.data.Data.OrderID,
                        addressInfo: self.data.defaultAddress,
                        RealityAmount: self.data.totalPrice
                      })
                    });
                    // wx.switchTab({
                    //   url: "/pages/mall/index/index"
                    // });
                  }
                })
              },
              'fail': function (_res) {
                wx.showToast({
                  title: '取消微信支付',
                  icon: 'none',
                  success: function () {
                    wx.redirectTo({
                      url: "/pages/myorderdetail/myorderdetail?orderId=" + res.data.Data.OrderID
                    });
                  }
                })
              },
              'complete': function (res) {
                  canClick=true;
              }
            })
            //购物车减去订单商品
            self.DeleteCart();
          } else {
            wx.showToast({
              title: res.data.Message,
              icon: 'none'
            })
            self.setData({
              erroMsg: res.data.Message
            });
            canClick = true;
          }
        }
      })

    } else {
      return
    }
  },
  DeleteCart:function(){
    var that = this;
    wx.getStorage({
      key: 'shopCart',
      success: function (res) {
        console.log(res);
        //删除
        var skuIdArr = [];
        for(var i=0;i<that.data.goodsList.length;i++)
        {
          skuIdArr.push(that.data.goodsList[i].Product_SkuId);
        }
        var list = spManger.ShopCartManagerClass.Instance.DeleteSkuBySkuIdArr(res.data,skuIdArr);
        //更新缓存
        wx.setStorage({
          key: 'shopCart',
          data: list,
          success: function (res) {
            console.log(res);
          }
        })
      }
    })
  },

  //备注
  RemarksChange(ev) {
    this.setData({
      RemarksValue: ev.detail.value
    });
  },

})